<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.0.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.0.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.0.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.0.4">


  <link rel="mask-icon" href="/images/logo.svg?v=6.0.4" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '6.0.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  
  <meta name="keywords" content="电商," />


<meta name="description" content="数据库设计：https://github.com/macrozheng/mall/blob/master/document/sql/mall.sql 状态订单状态 12@ApiModelProperty(value = &quot;订单状态：0-&amp;gt;待付款；1-&amp;gt;待发货；2-&amp;gt;已发货；3-&amp;gt;已完成；4-&amp;gt;已关闭；5-&amp;gt;无效订单&quot;)private Integer status">
<meta name="keywords" content="电商">
<meta property="og:type" content="article">
<meta property="og:title" content="mall开源电商学习笔记">
<meta property="og:url" content="http://blog.yunshu168.com/posts/13c83e4b.html">
<meta property="og:site_name" content="树下千云">
<meta property="og:description" content="数据库设计：https://github.com/macrozheng/mall/blob/master/document/sql/mall.sql 状态订单状态 12@ApiModelProperty(value = &quot;订单状态：0-&amp;gt;待付款；1-&amp;gt;待发货；2-&amp;gt;已发货；3-&amp;gt;已完成；4-&amp;gt;已关闭；5-&amp;gt;无效订单&quot;)private Integer status">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2020-03-09T08:18:29.642Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="mall开源电商学习笔记">
<meta name="twitter:description" content="数据库设计：https://github.com/macrozheng/mall/blob/master/document/sql/mall.sql 状态订单状态 12@ApiModelProperty(value = &quot;订单状态：0-&amp;gt;待付款；1-&amp;gt;待发货；2-&amp;gt;已发货；3-&amp;gt;已完成；4-&amp;gt;已关闭；5-&amp;gt;无效订单&quot;)private Integer status">






  <link rel="canonical" href="http://blog.yunshu168.com/posts/13c83e4b.html"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>
  <title>mall开源电商学习笔记 | 树下千云</title>
  






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?f8a99180bb75f49a4b2206cab6e25c50";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <!-- <div class="headband"></div>
<a href="https://github.com/yunshu2009"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a> -->
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">树下千云</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>


  



 </div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.yunshu168.com/posts/13c83e4b.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="云舒">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="树下千云">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">mall开源电商学习笔记</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <!--<span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>-->
              
                <!--<span class="post-meta-item-text">发表于</span>-->
              
              <!--<time title="创建于" itemprop="dateCreated datePublished" datetime="2019-10-03T20:26:57+08:00">2019-10-03</time>-->
            

            
            

            
          </span>

          

          
            
          

          
          

          


          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>数据库设计：<a href="https://github.com/macrozheng/mall/blob/master/document/sql/mall.sql" target="_blank" rel="noopener">https://github.com/macrozheng/mall/blob/master/document/sql/mall.sql</a></p>
<h3 id="状态"><a href="#状态" class="headerlink" title="状态"></a>状态</h3><p>订单状态</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@ApiModelProperty</span>(value = <span class="string">"订单状态：0-&gt;待付款；1-&gt;待发货；2-&gt;已发货；3-&gt;已完成；4-&gt;已关闭；5-&gt;无效订单"</span>)</span><br><span class="line"><span class="keyword">private</span> Integer status;</span><br></pre></td></tr></table></figure>
<p>订单退货申请状态<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@ApiModelProperty</span>(value = <span class="string">"申请状态：0-&gt;待处理；1-&gt;退货中；2-&gt;已完成；3-&gt;已拒绝"</span>)</span><br><span class="line"><span class="keyword">private</span> Integer status;</span><br></pre></td></tr></table></figure></p>
<p>优惠券使用状态 (在SmsCouponHistory实体中定义）<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@ApiModelProperty</span>(value = <span class="string">"使用状态：0-&gt;未使用；1-&gt;已使用；2-&gt;已过期"</span>)</span><br><span class="line"><span class="keyword">private</span> Integer useStatus;</span><br></pre></td></tr></table></figure></p>
<a id="more"></a>
<h3 id="订单超时操作设置表"><a href="#订单超时操作设置表" class="headerlink" title="订单超时操作设置表"></a>订单超时操作设置表</h3><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">create</span> <span class="keyword">table</span> oms_order_setting</span><br><span class="line">(</span><br><span class="line">   <span class="keyword">id</span>                   <span class="built_in">bigint</span> <span class="keyword">not</span> <span class="literal">null</span> auto_increment,</span><br><span class="line">   flash_order_overtime <span class="built_in">int</span> <span class="keyword">comment</span> <span class="string">'秒杀订单超时关闭时间(分)'</span>,</span><br><span class="line">   normal_order_overtime <span class="built_in">int</span> <span class="keyword">comment</span> <span class="string">'正常订单超时时间(分)'</span>,</span><br><span class="line">   confirm_overtime     <span class="built_in">int</span> <span class="keyword">comment</span> <span class="string">'发货后自动确认收货时间（天）'</span>,</span><br><span class="line">   finish_overtime      <span class="built_in">int</span> <span class="keyword">comment</span> <span class="string">'自动完成交易时间，不能申请售后（天）'</span>,</span><br><span class="line">   comment_overtime     <span class="built_in">int</span> <span class="keyword">comment</span> <span class="string">'订单完成后自动好评时间（天）'</span>,</span><br><span class="line">   primary <span class="keyword">key</span> (<span class="keyword">id</span>)</span><br><span class="line">);</span><br></pre></td></tr></table></figure>
<h3 id="订单编码生成"><a href="#订单编码生成" class="headerlink" title="订单编码生成"></a>订单编码生成</h3><p>18位订单编号:8位日期+2位平台号码+2位支付方式+6位以上自增id</p>
<p><a href="https://github.com/macrozheng/mall/blob/master/mall-portal/src/main/java/com/macro/mall/portal/service/impl/OmsPortalOrderServiceImpl.java" target="_blank" rel="noopener">https://github.com/macrozheng/mall/blob/master/mall-portal/src/main/java/com/macro/mall/portal/service/impl/OmsPortalOrderServiceImpl.java</a> :<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 生成18位订单编号:8位日期+2位平台号码+2位支付方式+6位以上自增id</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> String <span class="title">generateOrderSn</span><span class="params">(OmsOrder order)</span> </span>&#123;</span><br><span class="line">    StringBuilder sb = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">    String date = <span class="keyword">new</span> SimpleDateFormat(<span class="string">"yyyyMMdd"</span>).format(<span class="keyword">new</span> Date());</span><br><span class="line">    String key = REDIS_KEY_PREFIX_ORDER_ID + date;</span><br><span class="line">    Long increment = redisService.increment(key, <span class="number">1</span>);</span><br><span class="line">    sb.append(date);</span><br><span class="line">    sb.append(String.format(<span class="string">"%02d"</span>, order.getSourceType()));</span><br><span class="line">    sb.append(String.format(<span class="string">"%02d"</span>, order.getPayType()));</span><br><span class="line">    String incrementStr = increment.toString();</span><br><span class="line">    <span class="keyword">if</span> (incrementStr.length() &lt;= <span class="number">6</span>) &#123;</span><br><span class="line">        sb.append(String.format(<span class="string">"%06d"</span>, increment));</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        sb.append(incrementStr);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> sb.toString();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="商品-SKU-码生成"><a href="#商品-SKU-码生成" class="headerlink" title="商品 SKU 码生成"></a>商品 SKU 码生成</h3><p><a href="https://github.com/macrozheng/mall/blob/master/mall-admin/src/main/java/com/macro/mall/service/impl/PmsProductServiceImpl.java" target="_blank" rel="noopener">https://github.com/macrozheng/mall/blob/master/mall-admin/src/main/java/com/macro/mall/service/impl/PmsProductServiceImpl.java</a><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">handleSkuStockCode</span><span class="params">(List&lt;PmsSkuStock&gt; skuStockList, Long productId)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(CollectionUtils.isEmpty(skuStockList))<span class="keyword">return</span>;</span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>;i&lt;skuStockList.size();i++)&#123;</span><br><span class="line">        PmsSkuStock skuStock = skuStockList.get(i);</span><br><span class="line">        <span class="keyword">if</span>(StringUtils.isEmpty(skuStock.getSkuCode()))&#123;</span><br><span class="line">            SimpleDateFormat sdf = <span class="keyword">new</span> SimpleDateFormat(<span class="string">"yyyyMMdd"</span>);</span><br><span class="line">            StringBuilder sb = <span class="keyword">new</span> StringBuilder();</span><br><span class="line">            <span class="comment">//日期</span></span><br><span class="line">            sb.append(sdf.format(<span class="keyword">new</span> Date()));</span><br><span class="line">            <span class="comment">//四位商品id</span></span><br><span class="line">            sb.append(String.format(<span class="string">"%04d"</span>, productId));</span><br><span class="line">            <span class="comment">//三位索引id</span></span><br><span class="line">            sb.append(String.format(<span class="string">"%03d"</span>, i+<span class="number">1</span>));</span><br><span class="line">            skuStock.setSkuCode(sb.toString());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>商品sku编码为8位日期+至少4位商品ID+3位索引号</p>
<h3 id="查看确认单"><a href="#查看确认单" class="headerlink" title="查看确认单"></a>查看确认单</h3><p><a href="https://github.com/macrozheng/mall/blob/master/mall-portal/src/main/java/com/macro/mall/portal/service/impl/OmsPortalOrderServiceImpl.java" target="_blank" rel="noopener">https://github.com/macrozheng/mall/blob/master/mall-portal/src/main/java/com/macro/mall/portal/service/impl/OmsPortalOrderServiceImpl.java</a><br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> ConfirmOrderResult <span class="title">generateConfirmOrder</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    ConfirmOrderResult result = <span class="keyword">new</span> ConfirmOrderResult();</span><br><span class="line">    <span class="comment">//获取购物车信息</span></span><br><span class="line">    UmsMember currentMember = memberService.getCurrentMember();</span><br><span class="line">    List&lt;CartPromotionItem&gt; cartPromotionItemList = cartItemService.listPromotion(currentMember.getId());</span><br><span class="line">    result.setCartPromotionItemList(cartPromotionItemList);</span><br><span class="line">    <span class="comment">//获取用户收货地址列表</span></span><br><span class="line">    List&lt;UmsMemberReceiveAddress&gt; memberReceiveAddressList = memberReceiveAddressService.list();</span><br><span class="line">    result.setMemberReceiveAddressList(memberReceiveAddressList);</span><br><span class="line">    <span class="comment">//获取用户可用优惠券列表</span></span><br><span class="line">    List&lt;SmsCouponHistoryDetail&gt; couponHistoryDetailList = memberCouponService.listCart(cartPromotionItemList, <span class="number">1</span>);</span><br><span class="line">    result.setCouponHistoryDetailList(couponHistoryDetailList);</span><br><span class="line">    <span class="comment">//获取用户积分</span></span><br><span class="line">    result.setMemberIntegration(currentMember.getIntegration());</span><br><span class="line">    <span class="comment">//获取积分使用规则</span></span><br><span class="line">    UmsIntegrationConsumeSetting integrationConsumeSetting = integrationConsumeSettingMapper.selectByPrimaryKey(<span class="number">1L</span>);</span><br><span class="line">    result.setIntegrationConsumeSetting(integrationConsumeSetting);</span><br><span class="line">    <span class="comment">//计算总金额、活动优惠、应付金额</span></span><br><span class="line">    ConfirmOrderResult.CalcAmount calcAmount = calcCartAmount(cartPromotionItemList);</span><br><span class="line">    result.setCalcAmount(calcAmount);</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="下单"><a href="#下单" class="headerlink" title="下单"></a>下单</h3><p><a href="https://github.com/macrozheng/mall/blob/master/mall-portal/src/main/java/com/macro/mall/portal/service/impl/OmsPortalOrderServiceImpl.java" target="_blank" rel="noopener">https://github.com/macrozheng/mall/blob/master/mall-portal/src/main/java/com/macro/mall/portal/service/impl/OmsPortalOrderServiceImpl.java</a></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Override</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> CommonResult <span class="title">generateOrder</span><span class="params">(OrderParam orderParam)</span> </span>&#123;</span><br><span class="line">      List&lt;OmsOrderItem&gt; orderItemList = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">      <span class="comment">//获取购物车及优惠信息</span></span><br><span class="line">      UmsMember currentMember = memberService.getCurrentMember();</span><br><span class="line">      List&lt;CartPromotionItem&gt; cartPromotionItemList = cartItemService.listPromotion(currentMember.getId());</span><br><span class="line">      <span class="keyword">for</span> (CartPromotionItem cartPromotionItem : cartPromotionItemList) &#123;</span><br><span class="line">          <span class="comment">//生成下单商品信息</span></span><br><span class="line">          OmsOrderItem orderItem = <span class="keyword">new</span> OmsOrderItem();</span><br><span class="line">          orderItem.setProductId(cartPromotionItem.getProductId());</span><br><span class="line">          orderItem.setProductName(cartPromotionItem.getProductName());</span><br><span class="line">          orderItem.setProductPic(cartPromotionItem.getProductPic());</span><br><span class="line">          orderItem.setProductAttr(cartPromotionItem.getProductAttr());</span><br><span class="line">          orderItem.setProductBrand(cartPromotionItem.getProductBrand());</span><br><span class="line">          orderItem.setProductSn(cartPromotionItem.getProductSn());</span><br><span class="line">          orderItem.setProductPrice(cartPromotionItem.getPrice());</span><br><span class="line">          orderItem.setProductQuantity(cartPromotionItem.getQuantity());</span><br><span class="line">          orderItem.setProductSkuId(cartPromotionItem.getProductSkuId());</span><br><span class="line">          orderItem.setProductSkuCode(cartPromotionItem.getProductSkuCode());</span><br><span class="line">          orderItem.setProductCategoryId(cartPromotionItem.getProductCategoryId());</span><br><span class="line">          orderItem.setPromotionAmount(cartPromotionItem.getReduceAmount());</span><br><span class="line">          orderItem.setPromotionName(cartPromotionItem.getPromotionMessage());</span><br><span class="line">          orderItem.setGiftIntegration(cartPromotionItem.getIntegration());</span><br><span class="line">          orderItem.setGiftGrowth(cartPromotionItem.getGrowth());</span><br><span class="line">          orderItemList.add(orderItem);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">//判断购物车中商品是否都有库存</span></span><br><span class="line">      <span class="keyword">if</span> (!hasStock(cartPromotionItemList)) &#123;</span><br><span class="line">          <span class="keyword">return</span> CommonResult.failed(<span class="string">"库存不足，无法下单"</span>);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">//判断使用使用了优惠券</span></span><br><span class="line">      <span class="keyword">if</span> (orderParam.getCouponId() == <span class="keyword">null</span>) &#123;</span><br><span class="line">          <span class="comment">//不用优惠券</span></span><br><span class="line">          <span class="keyword">for</span> (OmsOrderItem orderItem : orderItemList) &#123;</span><br><span class="line">              orderItem.setCouponAmount(<span class="keyword">new</span> BigDecimal(<span class="number">0</span>));</span><br><span class="line">          &#125;</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">          <span class="comment">//使用优惠券</span></span><br><span class="line">          SmsCouponHistoryDetail couponHistoryDetail = getUseCoupon(cartPromotionItemList, orderParam.getCouponId());</span><br><span class="line">          <span class="keyword">if</span> (couponHistoryDetail == <span class="keyword">null</span>) &#123;</span><br><span class="line">              <span class="keyword">return</span> CommonResult.failed(<span class="string">"该优惠券不可用"</span>);</span><br><span class="line">          &#125;</span><br><span class="line">          <span class="comment">//对下单商品的优惠券进行处理</span></span><br><span class="line">          handleCouponAmount(orderItemList, couponHistoryDetail);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">//判断是否使用积分</span></span><br><span class="line">      <span class="keyword">if</span> (orderParam.getUseIntegration() == <span class="keyword">null</span>) &#123;</span><br><span class="line">          <span class="comment">//不使用积分</span></span><br><span class="line">          <span class="keyword">for</span> (OmsOrderItem orderItem : orderItemList) &#123;</span><br><span class="line">              orderItem.setIntegrationAmount(<span class="keyword">new</span> BigDecimal(<span class="number">0</span>));</span><br><span class="line">          &#125;</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">          <span class="comment">//使用积分</span></span><br><span class="line">          BigDecimal totalAmount = calcTotalAmount(orderItemList);</span><br><span class="line">          BigDecimal integrationAmount = getUseIntegrationAmount(orderParam.getUseIntegration(), totalAmount, currentMember, orderParam.getCouponId() != <span class="keyword">null</span>);</span><br><span class="line">          <span class="keyword">if</span> (integrationAmount.compareTo(<span class="keyword">new</span> BigDecimal(<span class="number">0</span>)) == <span class="number">0</span>) &#123;</span><br><span class="line">              <span class="keyword">return</span> CommonResult.failed(<span class="string">"积分不可用"</span>);</span><br><span class="line">          &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">              <span class="comment">//可用情况下分摊到可用商品中</span></span><br><span class="line">              <span class="keyword">for</span> (OmsOrderItem orderItem : orderItemList) &#123;</span><br><span class="line">                  BigDecimal perAmount = orderItem.getProductPrice().divide(totalAmount, <span class="number">3</span>, RoundingMode.HALF_EVEN).multiply(integrationAmount);</span><br><span class="line">                  orderItem.setIntegrationAmount(perAmount);</span><br><span class="line">              &#125;</span><br><span class="line">          &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">//计算order_item的实付金额</span></span><br><span class="line">      handleRealAmount(orderItemList);</span><br><span class="line">      <span class="comment">//进行库存锁定</span></span><br><span class="line">      lockStock(cartPromotionItemList);</span><br><span class="line">      <span class="comment">//根据商品合计、运费、活动优惠、优惠券、积分计算应付金额</span></span><br><span class="line">      OmsOrder order = <span class="keyword">new</span> OmsOrder();</span><br><span class="line">      order.setDiscountAmount(<span class="keyword">new</span> BigDecimal(<span class="number">0</span>));</span><br><span class="line">      order.setTotalAmount(calcTotalAmount(orderItemList));</span><br><span class="line">      order.setFreightAmount(<span class="keyword">new</span> BigDecimal(<span class="number">0</span>));</span><br><span class="line">      order.setPromotionAmount(calcPromotionAmount(orderItemList));</span><br><span class="line">      order.setPromotionInfo(getOrderPromotionInfo(orderItemList));</span><br><span class="line">      <span class="keyword">if</span> (orderParam.getCouponId() == <span class="keyword">null</span>) &#123;</span><br><span class="line">          order.setCouponAmount(<span class="keyword">new</span> BigDecimal(<span class="number">0</span>));</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">          order.setCouponId(orderParam.getCouponId());</span><br><span class="line">          order.setCouponAmount(calcCouponAmount(orderItemList));</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">if</span> (orderParam.getUseIntegration() == <span class="keyword">null</span>) &#123;</span><br><span class="line">          order.setIntegration(<span class="number">0</span>);</span><br><span class="line">          order.setIntegrationAmount(<span class="keyword">new</span> BigDecimal(<span class="number">0</span>));</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">          order.setIntegration(orderParam.getUseIntegration());</span><br><span class="line">          order.setIntegrationAmount(calcIntegrationAmount(orderItemList));</span><br><span class="line">      &#125;</span><br><span class="line">      order.setPayAmount(calcPayAmount(order));</span><br><span class="line">      <span class="comment">//转化为订单信息并插入数据库</span></span><br><span class="line">      order.setMemberId(currentMember.getId());</span><br><span class="line">      order.setCreateTime(<span class="keyword">new</span> Date());</span><br><span class="line">      order.setMemberUsername(currentMember.getUsername());</span><br><span class="line">      <span class="comment">//支付方式：0-&gt;未支付；1-&gt;支付宝；2-&gt;微信</span></span><br><span class="line">      order.setPayType(orderParam.getPayType());</span><br><span class="line">      <span class="comment">//订单来源：0-&gt;PC订单；1-&gt;app订单</span></span><br><span class="line">      order.setSourceType(<span class="number">1</span>);</span><br><span class="line">      <span class="comment">//订单状态：0-&gt;待付款；1-&gt;待发货；2-&gt;已发货；3-&gt;已完成；4-&gt;已关闭；5-&gt;无效订单</span></span><br><span class="line">      order.setStatus(<span class="number">0</span>);</span><br><span class="line">      <span class="comment">//订单类型：0-&gt;正常订单；1-&gt;秒杀订单</span></span><br><span class="line">      order.setOrderType(<span class="number">0</span>);</span><br><span class="line">      <span class="comment">//收货人信息：姓名、电话、邮编、地址</span></span><br><span class="line">      UmsMemberReceiveAddress address = memberReceiveAddressService.getItem(orderParam.getMemberReceiveAddressId());</span><br><span class="line">      order.setReceiverName(address.getName());</span><br><span class="line">      order.setReceiverPhone(address.getPhoneNumber());</span><br><span class="line">      order.setReceiverPostCode(address.getPostCode());</span><br><span class="line">      order.setReceiverProvince(address.getProvince());</span><br><span class="line">      order.setReceiverCity(address.getCity());</span><br><span class="line">      order.setReceiverRegion(address.getRegion());</span><br><span class="line">      order.setReceiverDetailAddress(address.getDetailAddress());</span><br><span class="line">      <span class="comment">//0-&gt;未确认；1-&gt;已确认</span></span><br><span class="line">      order.setConfirmStatus(<span class="number">0</span>);</span><br><span class="line">      order.setDeleteStatus(<span class="number">0</span>);</span><br><span class="line">      <span class="comment">//计算赠送积分</span></span><br><span class="line">      order.setIntegration(calcGifIntegration(orderItemList));</span><br><span class="line">      <span class="comment">//计算赠送成长值</span></span><br><span class="line">      order.setGrowth(calcGiftGrowth(orderItemList));</span><br><span class="line">      <span class="comment">//生成订单号</span></span><br><span class="line">      order.setOrderSn(generateOrderSn(order));</span><br><span class="line">      <span class="comment">// <span class="doctag">TODO:</span> 2018/9/3 bill_*,delivery_*</span></span><br><span class="line">      <span class="comment">//插入order表和order_item表</span></span><br><span class="line">      orderMapper.insert(order);</span><br><span class="line">      <span class="keyword">for</span> (OmsOrderItem orderItem : orderItemList) &#123;</span><br><span class="line">          orderItem.setOrderId(order.getId());</span><br><span class="line">          orderItem.setOrderSn(order.getOrderSn());</span><br><span class="line">      &#125;</span><br><span class="line">      orderItemDao.insertList(orderItemList);</span><br><span class="line">      <span class="comment">//如使用优惠券更新优惠券使用状态</span></span><br><span class="line">      <span class="keyword">if</span> (orderParam.getCouponId() != <span class="keyword">null</span>) &#123;</span><br><span class="line">          updateCouponStatus(orderParam.getCouponId(), currentMember.getId(), <span class="number">1</span>);</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">//如使用积分需要扣除积分</span></span><br><span class="line">      <span class="keyword">if</span> (orderParam.getUseIntegration() != <span class="keyword">null</span>) &#123;</span><br><span class="line">          order.setUseIntegration(orderParam.getUseIntegration());</span><br><span class="line">          memberService.updateIntegration(currentMember.getId(), currentMember.getIntegration() - orderParam.getUseIntegration());</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">//删除购物车中的下单商品</span></span><br><span class="line">      deleteCartItemList(cartPromotionItemList, currentMember);</span><br><span class="line">      <span class="comment">//发送延迟消息取消订单</span></span><br><span class="line">      sendDelayMessageCancelOrder(order.getId());</span><br><span class="line">      Map&lt;String, Object&gt; result = <span class="keyword">new</span> HashMap&lt;&gt;();</span><br><span class="line">      result.put(<span class="string">"order"</span>, order);</span><br><span class="line">      result.put(<span class="string">"orderItemList"</span>, orderItemList);</span><br><span class="line">      <span class="keyword">return</span> CommonResult.success(result, <span class="string">"下单成功"</span>);</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<h3 id="优惠券处理"><a href="#优惠券处理" class="headerlink" title="优惠券处理"></a>优惠券处理</h3><p><a href="https://github.com/macrozheng/mall/blob/master/mall-portal/src/main/java/com/macro/mall/portal/service/impl/OmsPortalOrderServiceImpl.java#handleCouponAmount" target="_blank" rel="noopener">https://github.com/macrozheng/mall/blob/master/mall-portal/src/main/java/com/macro/mall/portal/service/impl/OmsPortalOrderServiceImpl.java#handleCouponAmount</a></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br></pre></td><td class="code"><pre><span class="line"> <span class="comment">/**</span></span><br><span class="line"><span class="comment">  * 对优惠券优惠进行处理</span></span><br><span class="line"><span class="comment">  *</span></span><br><span class="line"><span class="comment">  * <span class="doctag">@param</span> orderItemList       order_item列表</span></span><br><span class="line"><span class="comment">  * <span class="doctag">@param</span> couponHistoryDetail 可用优惠券详情</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line"> <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">handleCouponAmount</span><span class="params">(List&lt;OmsOrderItem&gt; orderItemList, SmsCouponHistoryDetail couponHistoryDetail)</span> </span>&#123;</span><br><span class="line">     SmsCoupon coupon = couponHistoryDetail.getCoupon();</span><br><span class="line">     <span class="keyword">if</span> (coupon.getUseType().equals(<span class="number">0</span>)) &#123;</span><br><span class="line">         <span class="comment">//全场通用</span></span><br><span class="line">         calcPerCouponAmount(orderItemList, coupon);</span><br><span class="line">     &#125; <span class="keyword">else</span> <span class="keyword">if</span> (coupon.getUseType().equals(<span class="number">1</span>)) &#123;</span><br><span class="line">         <span class="comment">//指定分类</span></span><br><span class="line">         List&lt;OmsOrderItem&gt; couponOrderItemList = getCouponOrderItemByRelation(couponHistoryDetail, orderItemList, <span class="number">0</span>);</span><br><span class="line">         calcPerCouponAmount(couponOrderItemList, coupon);</span><br><span class="line">     &#125; <span class="keyword">else</span> <span class="keyword">if</span> (coupon.getUseType().equals(<span class="number">2</span>)) &#123;</span><br><span class="line">         <span class="comment">//指定商品</span></span><br><span class="line">         List&lt;OmsOrderItem&gt; couponOrderItemList = getCouponOrderItemByRelation(couponHistoryDetail, orderItemList, <span class="number">1</span>);</span><br><span class="line">         calcPerCouponAmount(couponOrderItemList, coupon);</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br><span class="line"> </span><br><span class="line"> <span class="comment">/**</span></span><br><span class="line"><span class="comment">  * 对每个下单商品进行优惠券金额分摊的计算</span></span><br><span class="line"><span class="comment">  *</span></span><br><span class="line"><span class="comment">  * <span class="doctag">@param</span> orderItemList 可用优惠券的下单商品商品</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line"> <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">calcPerCouponAmount</span><span class="params">(List&lt;OmsOrderItem&gt; orderItemList, SmsCoupon coupon)</span> </span>&#123;</span><br><span class="line">     BigDecimal totalAmount = calcTotalAmount(orderItemList);</span><br><span class="line">     <span class="keyword">for</span> (OmsOrderItem orderItem : orderItemList) &#123;</span><br><span class="line">         <span class="comment">//(商品价格/可用商品总价)*优惠券面额</span></span><br><span class="line">         BigDecimal couponAmount = orderItem.getProductPrice().divide(totalAmount, <span class="number">3</span>, RoundingMode.HALF_EVEN).multiply(coupon.getAmount());</span><br><span class="line">         orderItem.setCouponAmount(couponAmount);</span><br><span class="line">     &#125;</span><br><span class="line"> &#125;</span><br><span class="line"> </span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">  * 获取与优惠券有关系的下单商品</span></span><br><span class="line"><span class="comment">  *</span></span><br><span class="line"><span class="comment">  * <span class="doctag">@param</span> couponHistoryDetail 优惠券详情</span></span><br><span class="line"><span class="comment">  * <span class="doctag">@param</span> orderItemList       下单商品</span></span><br><span class="line"><span class="comment">  * <span class="doctag">@param</span> type                使用关系类型：0-&gt;相关分类；1-&gt;指定商品</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line"> <span class="function"><span class="keyword">private</span> List&lt;OmsOrderItem&gt; <span class="title">getCouponOrderItemByRelation</span><span class="params">(SmsCouponHistoryDetail couponHistoryDetail, List&lt;OmsOrderItem&gt; orderItemList, <span class="keyword">int</span> type)</span> </span>&#123;</span><br><span class="line">     List&lt;OmsOrderItem&gt; result = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">     <span class="keyword">if</span> (type == <span class="number">0</span>) &#123;</span><br><span class="line">         List&lt;Long&gt; categoryIdList = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">         <span class="keyword">for</span> (SmsCouponProductCategoryRelation productCategoryRelation : couponHistoryDetail.getCategoryRelationList()) &#123;</span><br><span class="line">             categoryIdList.add(productCategoryRelation.getProductCategoryId());</span><br><span class="line">         &#125;</span><br><span class="line">         <span class="keyword">for</span> (OmsOrderItem orderItem : orderItemList) &#123;</span><br><span class="line">             <span class="keyword">if</span> (categoryIdList.contains(orderItem.getProductCategoryId())) &#123;</span><br><span class="line">                 result.add(orderItem);</span><br><span class="line">             &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                 orderItem.setCouponAmount(<span class="keyword">new</span> BigDecimal(<span class="number">0</span>));</span><br><span class="line">             &#125;</span><br><span class="line">         &#125;</span><br><span class="line">     &#125; <span class="keyword">else</span> <span class="keyword">if</span> (type == <span class="number">1</span>) &#123;</span><br><span class="line">         List&lt;Long&gt; productIdList = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">         <span class="keyword">for</span> (SmsCouponProductRelation productRelation : couponHistoryDetail.getProductRelationList()) &#123;</span><br><span class="line">             productIdList.add(productRelation.getProductId());</span><br><span class="line">         &#125;</span><br><span class="line">         <span class="keyword">for</span> (OmsOrderItem orderItem : orderItemList) &#123;</span><br><span class="line">             <span class="keyword">if</span> (productIdList.contains(orderItem.getProductId())) &#123;</span><br><span class="line">                 result.add(orderItem);</span><br><span class="line">             &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                 orderItem.setCouponAmount(<span class="keyword">new</span> BigDecimal(<span class="number">0</span>));</span><br><span class="line">             &#125;</span><br><span class="line">         &#125;</span><br><span class="line">     &#125;</span><br><span class="line">     <span class="keyword">return</span> result;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<h3 id="使用-MongoDB-存储和查询浏览历史和收藏"><a href="#使用-MongoDB-存储和查询浏览历史和收藏" class="headerlink" title="使用 MongoDB 存储和查询浏览历史和收藏"></a>使用 MongoDB 存储和查询浏览历史和收藏</h3><h4 id="查询和添加浏览历史实现"><a href="#查询和添加浏览历史实现" class="headerlink" title="查询和添加浏览历史实现"></a>查询和添加浏览历史实现</h4><p>业务逻辑实现类<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Service</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MemberReadHistoryServiceImpl</span> <span class="keyword">implements</span> <span class="title">MemberReadHistoryService</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> MemberReadHistoryRepository memberReadHistoryRepository;</span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">create</span><span class="params">(MemberReadHistory memberReadHistory)</span> </span>&#123;</span><br><span class="line">        memberReadHistory.setId(<span class="keyword">null</span>);</span><br><span class="line">        memberReadHistory.setCreateTime(<span class="keyword">new</span> Date());</span><br><span class="line">        memberReadHistoryRepository.save(memberReadHistory);</span><br><span class="line">        <span class="keyword">return</span> <span class="number">1</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">delete</span><span class="params">(List&lt;String&gt; ids)</span> </span>&#123;</span><br><span class="line">        List&lt;MemberReadHistory&gt; deleteList = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">        <span class="keyword">for</span>(String id:ids)&#123;</span><br><span class="line">            MemberReadHistory memberReadHistory = <span class="keyword">new</span> MemberReadHistory();</span><br><span class="line">            memberReadHistory.setId(id);</span><br><span class="line">            deleteList.add(memberReadHistory);</span><br><span class="line">        &#125;</span><br><span class="line">        memberReadHistoryRepository.deleteAll(deleteList);</span><br><span class="line">        <span class="keyword">return</span> ids.size();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> List&lt;MemberReadHistory&gt; <span class="title">list</span><span class="params">(Long memberId)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> memberReadHistoryRepository.findByMemberIdOrderByCreateTimeDesc(memberId);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>MongoDB操作类 MemberReadHistoryRepository.java：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">MemberReadHistoryRepository</span> <span class="keyword">extends</span> <span class="title">MongoRepository</span>&lt;<span class="title">MemberReadHistory</span>,<span class="title">String</span>&gt; </span>&#123;</span><br><span class="line">    <span class="function">List&lt;MemberReadHistory&gt; <span class="title">findByMemberIdOrderByCreateTimeDesc</span><span class="params">(Long memberId)</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>实体类 MemberReadHistory：</p>
<p>文档对象的ID域添加@Id注解，需要检索的字段添加@Indexed注解。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.macro.mall.portal.domain;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> org.springframework.data.annotation.Id;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.mongodb.core.index.Indexed;</span><br><span class="line"><span class="keyword">import</span> org.springframework.data.mongodb.core.mapping.Document;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.Date;</span><br><span class="line"></span><br><span class="line"><span class="meta">@Document</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MemberReadHistory</span> </span>&#123;</span><br><span class="line">    <span class="meta">@Id</span></span><br><span class="line">    <span class="keyword">private</span> String id;</span><br><span class="line">    <span class="meta">@Indexed</span></span><br><span class="line">    <span class="keyword">private</span> Long memberId;</span><br><span class="line">    <span class="keyword">private</span> String memberNickname;</span><br><span class="line">    <span class="keyword">private</span> String memberIcon;</span><br><span class="line">    <span class="meta">@Indexed</span></span><br><span class="line">    <span class="keyword">private</span> Long productId;</span><br><span class="line">    <span class="keyword">private</span> String productName;</span><br><span class="line">    <span class="keyword">private</span> String productPic;</span><br><span class="line">    <span class="keyword">private</span> String productSubTitle;</span><br><span class="line">    <span class="keyword">private</span> String productPrice;</span><br><span class="line">    <span class="keyword">private</span> Date createTime;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getId</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> id;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setId</span><span class="params">(String id)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.id = id;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Long <span class="title">getMemberId</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> memberId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMemberId</span><span class="params">(Long memberId)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.memberId = memberId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getMemberNickname</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> memberNickname;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMemberNickname</span><span class="params">(String memberNickname)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.memberNickname = memberNickname;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getMemberIcon</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> memberIcon;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setMemberIcon</span><span class="params">(String memberIcon)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.memberIcon = memberIcon;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Long <span class="title">getProductId</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> productId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setProductId</span><span class="params">(Long productId)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.productId = productId;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getProductName</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> productName;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setProductName</span><span class="params">(String productName)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.productName = productName;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getProductPic</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> productPic;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setProductPic</span><span class="params">(String productPic)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.productPic = productPic;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getProductSubTitle</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> productSubTitle;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setProductSubTitle</span><span class="params">(String productSubTitle)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.productSubTitle = productSubTitle;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> String <span class="title">getProductPrice</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> productPrice;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setProductPrice</span><span class="params">(String productPrice)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.productPrice = productPrice;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> Date <span class="title">getCreateTime</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> createTime;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setCreateTime</span><span class="params">(Date createTime)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>.createTime = createTime;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>具体参考：<a href="http://www.macrozheng.com/#/architect/mall_arch_08" target="_blank" rel="noopener">http://www.macrozheng.com/#/architect/mall_arch_08</a></p>
<h3 id="使用-ElasticSearch-实现商品搜索"><a href="#使用-ElasticSearch-实现商品搜索" class="headerlink" title="使用 ElasticSearch 实现商品搜索"></a>使用 ElasticSearch 实现商品搜索</h3><p>先将商品信息导入到 ElasticSearch ，然后使用 ElasticSearch 搜索。</p>
<p>导入：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">importAll</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    List&lt;EsProduct&gt; esProductList = productDao.getAllEsProductList(<span class="keyword">null</span>);</span><br><span class="line">    Iterable&lt;EsProduct&gt; esProductIterable = productRepository.saveAll(esProductList);</span><br><span class="line">    Iterator&lt;EsProduct&gt; iterator = esProductIterable.iterator();</span><br><span class="line">    <span class="keyword">int</span> result = <span class="number">0</span>;</span><br><span class="line">    <span class="keyword">while</span> (iterator.hasNext()) &#123;</span><br><span class="line">        result++;</span><br><span class="line">        iterator.next();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>搜索：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> Page&lt;EsProduct&gt; <span class="title">search</span><span class="params">(String keyword, Integer pageNum, Integer pageSize)</span> </span>&#123;</span><br><span class="line">    Pageable pageable = PageRequest.of(pageNum, pageSize);</span><br><span class="line">    <span class="keyword">return</span> productRepository.findByNameOrSubTitleOrKeywords(keyword, keyword, keyword, pageable);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>更多参考：<a href="http://www.macrozheng.com/" target="_blank" rel="noopener">http://www.macrozheng.com/</a></p>

      
    </div>

    

    
    
    
<div>
  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">------本文结束<i class="fa fa-paw"></i>感谢阅读------</div>
    
</div>
  
</div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>欣赏此文？求鼓励，求支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat.png" alt="云舒 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="云舒 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>云舒</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://blog.yunshu168.com/posts/13c83e4b.html" title="mall开源电商学习笔记">http://blog.yunshu168.com/posts/13c83e4b.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/电商/" rel="tag"># 电商</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/59754ac1.html" rel="next" title="订单号生成实例">
                <i class="fa fa-chevron-left"></i> 订单号生成实例
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/74af3221.html" rel="prev" title="从零开始搭建创业公司技术架构">
                从零开始搭建创业公司技术架构 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        
  <div class="bdsharebuttonbox">
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
    <a href="#" class="bds_douban" data-cmd="douban" title="分享到豆瓣网"></a>
    <a href="#" class="bds_sqq" data-cmd="sqq" title="分享到QQ好友"></a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a>
    <a href="#" class="bds_tieba" data-cmd="tieba" title="分享到百度贴吧"></a>
    <a href="#" class="bds_twi" data-cmd="twi" title="分享到Twitter"></a>
    <a href="#" class="bds_fbook" data-cmd="fbook" title="分享到Facebook"></a>
    <a href="#" class="bds_more" data-cmd="more"></a>
    <a class="bds_count" data-cmd="count"></a>
  </div>
  <script>
    window._bd_share_config = {
      "common": {
        "bdText": "",
        "bdMini": "2",
        "bdMiniList": false,
        "bdPic": ""
      },
      "share": {
        "bdSize": "16",
        "bdStyle": "0"
      },
      "image": {
        "viewList": ["tsina", "douban", "sqq", "qzone", "weixin", "twi", "fbook"],
        "viewText": "分享到：",
        "viewSize": "16"
      }
    }
  </script>

<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      
        <div id="gitment-container"></div>
      
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="云舒" />
            
              <p class="site-author-name" itemprop="name">云舒</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives">
                
                    <span class="site-state-item-count">68</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">5</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">28</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/yunshu2009" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:yunshu.luo@gmail.com" target="_blank" title="E-Mail"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.cnblogs.com/luoyunshu/" target="_blank" title="Cnblogs"><i class="fa fa-fw fa-globe"></i>Cnblogs</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.bilibili.com" target="_blank" title="bilibili"><i class="fa fa-fw fa-globe"></i>bilibili</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#状态"><span class="nav-number">1.</span> <span class="nav-text">状态</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#订单超时操作设置表"><span class="nav-number">2.</span> <span class="nav-text">订单超时操作设置表</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#订单编码生成"><span class="nav-number">3.</span> <span class="nav-text">订单编码生成</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#商品-SKU-码生成"><span class="nav-number">4.</span> <span class="nav-text">商品 SKU 码生成</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#查看确认单"><span class="nav-number">5.</span> <span class="nav-text">查看确认单</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#下单"><span class="nav-number">6.</span> <span class="nav-text">下单</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#优惠券处理"><span class="nav-number">7.</span> <span class="nav-text">优惠券处理</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用-MongoDB-存储和查询浏览历史和收藏"><span class="nav-number">8.</span> <span class="nav-text">使用 MongoDB 存储和查询浏览历史和收藏</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#查询和添加浏览历史实现"><span class="nav-number">8.1.</span> <span class="nav-text">查询和添加浏览历史实现</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用-ElasticSearch-实现商品搜索"><span class="nav-number">9.</span> <span class="nav-text">使用 ElasticSearch 实现商品搜索</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2012 &mdash; <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">云舒</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Pisces</a></div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.0.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.0.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.0.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.0.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.4"></script>



  



	





  





  






<!-- LOCAL: You can save these files to your site and update links -->
    
        
         <!-- <link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css"> -->
        <!-- <script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script> -->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/theme-next/theme-next-gitment@1/default.css">
        <script src="https://cdn.jsdelivr.net/gh/theme-next/theme-next-gitment@1/gitment.browser.js"></script>
    
<!-- END LOCAL -->

    

    
      <script type="text/javascript">
      function renderGitment(){
        var gitment = new Gitment({
            id: decodeURI(window.location.pathname),
            owner: 'yunshu2009',
            repo: 'yunshu2009.github.io',
            
            oauth: {
            
            
                client_secret: '15cdd9dc30fb9e0c97260bf79fe09d158fa04b22',
            
                client_id: '9495da16cda475a5e221'
            }});
        gitment.render('gitment-container');
      }

      
      renderGitment();
      
      </script>
    






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  


</body>
</html>
